<template>
  <div class="container">
    <div class="canvas" ref="canvas"></div>
    <div id="js-properties-panel" class="panel"></div>

    <input
        type="file"
        ref="fileInput"
        hidden
        accept=".xml,.bpmn"
        @change="handleFileUpload"
    >
  </div>
  <el-button type="primary" @click="goBack()">回到首页</el-button>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import BpmnModeler from "bpmn-js/lib/Modeler"
import { xmlStr } from "@/activiti/js/xmlStr.js"
import propertiesPanelModule from "bpmn-js-properties-panel"
import propertiesProviderModule from "bpmn-js-properties-panel/lib/provider/camunda"
import camundaModdleDescriptor from "camunda-bpmn-moddle/resources/camunda"
import { customTranslate } from "@/activiti/js/translations.js"
import axios from "axios"
import router from "@/router/index.js";
import request from "@/util/request.js";

const route = useRoute()
const canvas = ref(null)
const fileInput = ref(null)
const bpmnModeler = ref(null)
const errorMessage = ref('')

let  xml  = route.query.xml
// 初始化BPMN建模器
const init = () => {
  bpmnModeler.value = new BpmnModeler({
    container: canvas.value,
    propertiesPanel: {
      parent: "#js-properties-panel",
    },
    additionalModules: [
      propertiesProviderModule,
      propertiesPanelModule,
      { translate: ["value", customTranslate] }
    ],
    moddleExtensions: {
      camunda: camundaModdleDescriptor
    }
  })

  bpmnModeler.value.importXML(xmlStr, (err) => {
    if (err) {
      console.error(err)
    } else {
      console.log("BPMN diagram rendered")
    }
  })
}

// 导出XML
const exportXML = async () => {
  bpmnModeler.value.saveXML({ format: true }, async (err, xml) => {
    if (err) return console.error(err)

    try {
      const res = await request.post('workflowDesign/workFlow/exportWorkFlow', {
        name: "入库申请",
        type: 1,
        orderId: 1,
        xml: xml + ""
      }, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      })

      res.data.data
          ? ElMessage.success("导出成功")
          : ElMessage.error("导出失败")
    } catch (error) {
      ElMessage.error("导出请求失败")
    }
  })
}

// 触发文件选择
const triggerFileSelect = () => {
  fileInput.value.click()
}

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return

  errorMessage.value = ''
  if (!validateFile(file)) {
    errorMessage.value = '仅支持 .xml 或 .bpmn 文件'
    return
  }

  const reader = new FileReader()
  reader.onload = async (e) => {
    try {
      await renderBpmnDiagram(e.target.result)
    } catch (err) {
      handleError(err)
    }
  }
  reader.onerror = handleError
  reader.readAsText(file)
}
const goBack = () => {
  router.replace('/home/workflow/page')
}
// 校验文件
const validateFile = (file) => {
  return /\.(bpmn|xml)$/i.test(file.name)
}

// 渲染流程图
const renderBpmnDiagram = async (xmlString) => {
  try {
    const { warnings } = await bpmnModeler.value.importXML(xmlString)
    if (warnings.length) {
      console.warn('BPMN警告:', warnings)
    }
    bpmnModeler.value.get('canvas').zoom('fit-viewport')
  } catch (err) {
    handleError(err)
  }
}

// 错误处理
const handleError = (error) => {
  console.error('错误:', error)
  errorMessage.value = parseErrorMessage(error)
  fileInput.value.value = ''
}

// 解析错误信息
const parseErrorMessage = (error) => {
  if (error.message.includes('Unsupported XML')) return '无效的BPMN XML格式'
  if (error.message.includes('parsing error')) return 'XML解析错误'
  return '文件处理失败'
}

// 预览
const preview = () => {
  const xmlString = `<?xml version="1.0" encoding="UTF-8"?>...` // 保持原XML字符串
  bpmnModeler.value.importXML(xmlString, (err) => {
    err ? console.error(err) : console.log("Preview rendered")
  })
}

const preview1 = () => {
  const xmlString = xml // 保持原XML字符串
  bpmnModeler.value.importXML(xmlString, (err) => {
    err ? console.error(err) : console.log("Preview rendered")
  })
}


// 初始化组件
onMounted(() => {
  init()
  preview1()
})
</script>

<style scoped>
/* 保持原有样式不变 */
.container {
  width: 100%;
  height: 1000px;
  position: relative;
}
.canvas {
  width: 100%;
  height: 100%;
  background: white;
}
.panel {
  position: absolute;
  top: 0;
  right: 0;
  width: 300px;
}
.btm {
  position: absolute;
  left: 0px;
  top: 700px;
}
.error-msg {
  position: absolute;
  top: -20px;
  left: 120px;
  padding: 8px 16px;
  background: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
  border-radius: 4px;
  max-width: 300px;
}
.btm1 {
  position: absolute;
  left: 0px;
  top: 750px;
}
.btm2 {
  position: absolute;
  left: 0px;
  top: 800px;
}
</style>
